package com.freemypay.test.并发.加入一个线程;

/**
 * join() 等待该线程终止。
 * 抛出：InterruptedException - 如果任何线程中断了当前线程。当抛出该异常时，当前线程的中断状态 被清除。
 * @author yesixian
 * @date 2018年5月14日
 */
public class Joining {
	public static void main(String[] args) {
		Sleeper sleepy = new Sleeper("Sleepy", 1500);
		Sleeper grumpy = new Sleeper("Grumpy", 1500);
		Joiner dopey = new Joiner("Dopey", sleepy);
		Joiner doc = new Joiner("Doc", grumpy);
		grumpy.interrupt();
	}
}

class Sleeper extends Thread {
	private int duration;
	
	public Sleeper(String name, int sleepTime) {
		super(name);
		duration = sleepTime;
		start();
	}
	
	@Override
	public void run() {
		try {
			sleep(duration);
		} catch (InterruptedException e) {
			/*
			 * 其他线程调用该线程interrupt()方法,catch中清理该标志,所以catch中总是为false.
			 * Grumpy was interrupted. isInterrupted(): false
			 * Doc join completed
			 * Sleepy has awakened
			 * Dopey join completed
			 */
			System.out.println(getName() + " was interrupted. " +
					"isInterrupted(): " + isInterrupted());
			return;
		}
		System.out.println(getName() + " has awakened");
	}
}

class Joiner extends Thread {
	private Sleeper sleeper;
	
	public Joiner(String name, Sleeper sleeper) {
		super(name);
		this.sleeper = sleeper;
		start();
	}
	
	@Override
	public void run() {
		try {
			sleeper.join();
		} catch (InterruptedException e) {
			System.out.println("Interrupted");
		}
		System.out.println(getName() + " join completed");
	}
}
